package procilege.lang;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class PrivExprComposition implements PrivExprElement,
		CompositeExpr<PrivExprElement> {

	private Set<PrivExprElement> terms = new HashSet<PrivExprElement>();

	public PrivExprComposition() {
	}

	public PrivExprComposition(Collection<PrivExprElement> terms) {

		for (PrivExprElement t : terms) {
			compose(t);
		}
	}

	public int size() {
		return terms.size();
	}

	public void compose(PrivExprElement pt) {

		if (pt == null)
			return;

		if (pt instanceof PrivExprComposition) {

			for (PrivExprElement t : ((PrivExprComposition) pt).terms) {

				terms.add(t);
			}
		} else if (pt instanceof PrivExprElement) {

			terms.add(pt);
		} else
			throw new UnsupportedOperationException("unknown: " + pt);
	}

	public Collection<PrivExprElement> getTerms() {
		return terms;
	}

	public void add(PrivExprElement elem) {

		compose(elem);
	}

	public Iterator<PrivExprElement> iterator() {
		return terms.iterator();
	}

	@Override
	public int hashCode() {
		final int PRIME = 31;
		int result = 1;
		result = PRIME * result + ((terms == null) ? 0 : terms.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final PrivExprComposition other = (PrivExprComposition) obj;
		if (terms == null) {
			if (other.terms != null)
				return false;
		} else if (!terms.equals(other.terms))
			return false;
		return true;
	}
}
